/**
 * 解析字幕文件内容为数组
 * @param content 字幕文件内容
 */
export function parseSubtitle(content: string): Api.Translation.SubtitleItem[] {
    const lines = content.split('\n');
    const subtitles: Api.Translation.SubtitleItem[] = [];
    let currentSubtitle: Partial<Api.Translation.SubtitleItem> = {};
    let id = 1;

    for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim();

        // 跳过空行
        if (!line) continue;

        // 字幕序号
        if (/^\d+$/.test(line)) {
            if (currentSubtitle.text) {
                subtitles.push(currentSubtitle as Api.Translation.SubtitleItem);
            }
            currentSubtitle = { id: id++ };
            continue;
        }

        // 时间轴
        const timeMatch = line.match(/(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})/);
        if (timeMatch) {
            currentSubtitle.startTime = timeMatch[1];
            currentSubtitle.endTime = timeMatch[2];
            continue;
        }

        // 字幕文本
        if (currentSubtitle.startTime && currentSubtitle.endTime) {
            if (!currentSubtitle.text) {
                currentSubtitle.text = line;
            } else {
                currentSubtitle.text += '\n' + line;
            }
        }
    }

    // 添加最后一条字幕
    if (currentSubtitle.text) {
        subtitles.push(currentSubtitle as Api.Translation.SubtitleItem);
    }

    return subtitles;
}

/**
 * 生成字幕文件内容
 * @param subtitles 字幕数组
 */
export function generateSubtitleFile(subtitles: Api.Translation.SubtitleItem[]): string {
    return subtitles
        .map(subtitle => {
            return [
                subtitle.id,
                `${subtitle.startTime} --> ${subtitle.endTime}`,
                subtitle.translation || subtitle.text,
                '' // 空行分隔
            ].join('\n');
        })
        .join('\n');
} 